<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="请输入要bb的内容（最多吐槽120字）" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,i) in comments" :key="item.add_time">
        <div
          class="cmt-title"
        >第{{i+1}}楼 &nbsp;&nbsp;用户：{{item.name}}&nbsp;&nbsp;发表时间：{{item.add_time |dataFormat}}</div>
        <div
          class="cmt-body"
        >{{item.commentcontent==='undefind' ? '此用户很赖，啥都没说':item.commentcontent}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
    <!-- plain是幽灵按钮 
    size3属性：small large 
    背景色：蓝色primary 红色danger-->
  </div>
</template>
<script>
import { Toast } from "mint-ui"; //因为要弹出“获取评论失败”，所以要导入
export default {
  data() {
    return {
      pageIndex: 1, //默认展示第一页数据
      comments: [], //所有的评论数据
      msg: "" //评论输入的内容
    };
  },
  created() {
    this.getComment();
  },
  methods: {
    getComment() {
      //获取评论
      this.$http
        .get(
          "http://localhost:3000/src/db/comment.json?id=" +
            this.id +
            "&pageindex=" +
            this.pageIndex
        )
        .then(result => {
          /*
                if(result.body.status===0){
                    //每当获取新评论数据的时候，不要把老数据清空覆盖，是要新+老，拼接的方式拼接新数据
                    this.comments=this.comments.concat(result.body.content);
                }else{
                    Toast('获取评论失败')
                */

          console.log(result);
          this.comments = result.body;
        });
    },
    getMore() {
      //加载更多
      this.pageIndex++;
      this.getComment();
    },
    postComment() {
      //校验是否为空内容
      if (this.msg.trim().length === 0) {
        return Toast("评论内容不能为空");
      }
      //发表评论
      this.$http
        .get("http://localhost:3000/src/db/postcomment.json?id=" + this.id, {
          content: this.msg.trim()
        })
        .then(function(result) {
          /* if (result.body.status === 0) {
            
          } */
          //拼接出一个评论对象
          //var test=result.body.content;
            var cmt = {
              name: "匿名用户1",
              add_time: Date.now(),
              commentcontent: this.msg.trim()
            };
            console.log(this.comments);
            this.comments.unshift(cmt);
            this.msg = "";
        });
    }
  }
};
props: ["id"];
</script>
<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }
  .cmt-list {
    margin: 5px 0;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        background-color: #ccc;
        line-height: 30px;
      }
      .cmt-body {
        line-height: 40px;
        text-indent: 2em; //缩进
      }
    }
  }
}
</style>